package com.example.xmhds_1.mapper.userinfo;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.xmhds_1.entity.GroupChat;
import org.apache.ibatis.annotations.*;
import java.util.*;

/**
 * 群聊数据访问接口
 */
@Mapper
public interface GroupChatMapper extends BaseMapper<GroupChat> {

    /**
     * 创建群聊
     *
     * @param groupChat 群聊信息
     * @return 影响的行数
     */
    @Insert("INSERT INTO group_chat (group_id, group_name, members, messages, " +
            "create_time, update_time, deleted) " +
            "VALUES (#{groupId}, #{groupName}, #{members}, #{messages}, " +
            "#{createTime}, #{updateTime}, #{deleted})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(GroupChat groupChat);

    /**
     * 根据群ID获取群聊信息
     *
     * @param groupId 群ID
     * @return 群聊信息
     */
    @Select("SELECT * FROM group_chat WHERE group_id = #{groupId} AND deleted = 0")
    GroupChat getByGroupId(@Param("groupId") String groupId);

    /**
     * 更新群聊信息
     *
     * @param groupChat 群聊信息
     * @return 影响的行数
     */
    @Update("UPDATE group_chat SET " +
            "group_name = #{groupName}, " +
            "members = #{members}, " +
            "messages = #{messages}, " +
            "update_time = #{updateTime} " +
            "WHERE id = #{id} AND deleted = 0")
    int updateById(GroupChat groupChat);

    /**
     * 逻辑删除群聊
     *
     * @param id 群聊ID
     * @return 影响的行数
     */
    @Update("UPDATE group_chat SET deleted = 1, update_time = NOW() " +
            "WHERE id = #{id} AND deleted = 0")
    int deleteById(@Param("id") Long id);

    /**
     * 获取所有群聊
     */
    @Select("SELECT * FROM group_chat WHERE deleted = 0")
    List<GroupChat> getAllGroup();

    /**
     * 根据用户账号查询聊天记录
     */
    @Select("SELECT gc.* FROM group_chat gc " +
            "INNER JOIN user_account ua1 ON ua1.account = #{account1} " +
            "INNER JOIN user_account ua2 ON ua2.account = #{account2} " +
            "WHERE (gc.user_0 = ua1.id AND gc.user_1 = ua2.id) " +
            "   OR (gc.user_0 = ua2.id AND gc.user_1 = ua1.id) " +
            "AND gc.deleted = 0 " +
            "LIMIT 1")
    GroupChat getChatByAccounts(String account1, String account2);

    /**
     * 根据两个用户ID查询聊天记录
     */
    @Select("SELECT * FROM group_chat " +
            "WHERE (user_0 = #{userId1} AND user_1 = #{userId2}) " +
            "   OR (user_0 = #{userId2} AND user_1 = #{userId1}) " +
            "AND deleted = 0 " +
            "LIMIT 1")
    GroupChat getChatByUserIds(String userId1, String userId2);
}
